﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <canvas width="600" height="300" id="drawing" style=" border:1px solid red"></canvas>

    <div>
        <h1>绘制矩形</h1>
        <table>
            <tr>
                <td>坐标</td>
                <td>
                    <ul>
                        <li>
                            <span>x:</span><input type="number" id="positionX" />
                        </li>
                        <li>
                            <span>y:</span><input type="number" id="positionY" />
                        </li>
                    </ul>
                </td>
            </tr>
            <tr>
                <td>大小</td>
                <td>
                    <ul>
                        <li>
                            <span>width:</span><input type="number" id="width" />
                        </li>
                        <li>
                            <span>height:</span><input type="number" id="height" />
                        </li>
                    </ul>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="button" value="填充绘制" onclick="drawRect('fill')" style="padding-right : 10px" />
                    <input type="button" value="描边绘制" onclick="drawRect('stroke')" style="padding-right : 10px" />
                </td>
            </tr>
        </table>
    </div>
    <script type="text/javascript">
        //初始化上下文
        window.onload = function () {
            var canvas = document.getElementById("drawing");
            if (canvas.getContext) {
                var content = canvas.getContext("2d");
                content.fillStyle = "blue";
                content.strokeStyle = "red";
            }
        }

       
        function drawRect(mode) {
            var canvas = document.getElementById("drawing");

            if (canvas.getContext) {
                var content = canvas.getContext("2d");
                var
                 x = Number(document.getElementById("positionX").value) || 0,
                 y = Number(document.getElementById("positionY").value) || 0,
                 width = Number(document.getElementById("width").value) || 100,
                 height = Number(document.getElementById("height").value) || 100;

                
                if (mode == "fill") {
                    content.fillRect(x, y, width, height);
                } else {
                    content.strokeRect(x, y, width, height);
                }
               
            }
        }
    </script>
</body>
</html>
